package com.example.demo01.base.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Author : hzq
 * @Date : 2020-04-28
 * @Project: demo01
 */
public class SessionInterceptor implements HandlerInterceptor {

    /**
     * Description: 根据session进行拦截并重定向请求
     *
     * @param request:
     * @param response:
     * @param handler:
     * @return boolean
     * @author houzq
     * @data 2020/10/15
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("request.getRequestURI(): " + requestURI);
        // 登录链接不做拦截
        if (("/login/toLogin").equals(requestURI) || ("/login/loginIn").equals(requestURI) || ("/index/toIndex").equals(requestURI)) {
            return true;
        }

        // 判断登录会话是否存在，如果不存在，拦截去其他jsp页面的请求
        Object object = request.getSession().getAttribute("username");
        if (object == null) {
            response.sendRedirect("/login/toLogin");
            return false;
        }

        return true;
    }
}
